package com.moon.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.moon.R;
import com.moon.common.ManagedGoogleTracker;
import com.moon.model.UpdateFeedback;
import com.moon.utils.UpdateUtil.DownloadProgressCallback;



/**
 * 版本更新工具
 * 
 * 
 * @author paul
 * @date 2014年5月25日
 */
public class UpdateCheckerUtils {
    private static final String  TAG                 = UpdateCheckerUtils.class.getSimpleName();
    /** 超过7天才进行自动更新 */
    private static final String  LAST_CHECK_TIME_KEY = "lastCheckTime";
    private Activity             activity;
    private boolean              checked             = false;
    private boolean              updateAvailable     = false;
    private UpdateFeedback       feedback            = null;
    private DownloadTask         downloadTask;
    private ProgressDialog       checkingProgress;
    private boolean              autoCheck           = false;
    private ManagedGoogleTracker tracker;

    public UpdateCheckerUtils(Activity activity) {
        this.activity = activity;
        this.tracker = ManagedGoogleTracker.getInstance(activity.getApplication());
        this.checkingProgress = new ProgressDialog(activity);
        checkingProgress.setMessage(activity.getText(R.string.checking_update));
    }

    /**
     * 检查更新
     * 
     * @param autoCheck 是否是自动更新
     */
    public void startCheckUpdate(boolean autoCheck) {
        //TODO 后面恢复
//        if (!doUpdate(autoCheck)) {
//            return;
//        }
        this.autoCheck = autoCheck;

        // 保存最后一次更新时间
        saveLastCheckTime(System.currentTimeMillis());
        if (!autoCheck) {
            checkingProgress.show();
        }
        if (!checked) {
            new Thread(new CheckTask()).start();
        } else {
            showUpdateDialogIfAvailable();
        }
    }

    private class CheckTask implements Runnable {
        @Override
        public void run() {
            try {
                checked = true;
                UpdateFeedback feedback = UpdateUtil.checkUpdate();
                if (feedback == null) {
                    checked = false;
                    return;
                } else {
                    UpdateCheckerUtils.this.feedback = feedback;
                }
                int curVersion = UpdateUtil.getVersionCode(activity);
                int newVersion = feedback.getVersionCode();
                if (newVersion > curVersion) {
                    updateAvailable = true;
                } else {
                    updateAvailable = false;
                }
                showUpdateDialogIfAvailable();
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
                checked = false;
                checkingProgress.dismiss();
                if (!autoCheck) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(activity,  R.string.network_error, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }
    }

    private class DownloadTask extends AsyncTask<String, Integer, String> {
        private ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(activity);
            pd.setTitle(R.string.download);
            pd.setMessage(activity.getText(R.string.downloading));
            pd.setIndeterminate(false);
            pd.setMax(feedback.getFileSize());
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setCancelable(true);
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    DownloadTask.this.cancel(true);
                }
            });
            pd.show();
        }

        protected String doInBackground(String... params) {
            try {
                DownloadProgressCallback callback = new DownloadProgressCallback() {
                    @Override
                    public void publish(int sizeDownloaded) {
                        DownloadTask.this.publishProgress(sizeDownloaded);
                    }
                };
                return UpdateUtil.downloadFile(feedback.getApkUrl(), feedback.getVersionName(), callback);
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(activity,  R.string.download_failed, Toast.LENGTH_SHORT).show();
                    }
                });
                return null;
            }
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            // 更新进度条
            pd.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            pd.dismiss();
            if (!TextUtils.isEmpty(result)) {
                // 安装软件
                try {
                    UpdateUtil.installApk(activity, result);
                } catch (Exception e) {
                    Toast.makeText(activity,  R.string.install_failed, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private void showUpdateDialogIfAvailable() {
        checkingProgress.dismiss();
        checked = false;
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (updateAvailable) {
                    String message = activity.getString(R.string.update_available_tip,
                            UpdateUtil.getVersionName(activity), feedback.getVersionName());
                    new AlertDialog.Builder(activity).setTitle(R.string.check_update)
                            .setMessage(message)
                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int whichButton) {
                                    tracker.trackEvent("Click", "DownloadApk", "UpdateChecker", 1);
                                    downloadApk();
                                }
                            }).setNegativeButton(R.string.cancel, null).show();
                } else if (!autoCheck) {
                    new AlertDialog.Builder(activity).setTitle(R.string.check_update)
                            .setMessage(R.string.no_update_available_tip)
                            .setNeutralButton(R.string.ok, null).show();
                }
            }
        });
    }

    private void downloadApk() {
        if (downloadTask != null && downloadTask.getStatus() == Status.RUNNING) {
            return;
        }
        downloadTask = new DownloadTask();
        downloadTask.execute(feedback.getApkUrl());
    }

//    private boolean doUpdate(boolean autoCheck) {
//        if (!autoCheck) {
//            return true;
//        }
//        if (autoCheckUpdateWifiOnly(activity) && !isWifi()) {
//            // 只在wifi网络下进行自动检查更新
//            return false;
//        }
//
//        // 判断最后一次更新时间
//        int intervalDays = getAutoCheckIntervalDays(activity);
//        if (intervalDays < 0) {
//            // <0 表示从不检查更新
//            return false;
//        }
//        int millSeconds = intervalDays * 24 * 60 * 60 * 1000;
//        return getLastCheckTime() + millSeconds <= System.currentTimeMillis();
//    }

//    private boolean isWifi() {
//        ConnectivityManager connectivityManager = (ConnectivityManager) activity
//                .getSystemService(Context.CONNECTIVITY_SERVICE);
//        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
//            return true;
//        }
//        return false;
//    }
//
//    private long getLastCheckTime() {
//        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
//        // 如果是第一次就返回0，即会立即执行检查（自动模式下）
//        return preferences.getLong(LAST_CHECK_TIME_KEY, 0);
//    }

    private void saveLastCheckTime(long lastCheckTime) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
        Editor edit = preferences.edit();
        edit.putLong(LAST_CHECK_TIME_KEY, lastCheckTime);
        edit.commit();
    }
    
//    /**
//     * 自动检查更新功能是否仅在WIFI网络下进行  --来自SettingsPreferenceActivity
//     */
//    private static boolean autoCheckUpdateWifiOnly(Context context) {
//      return true;
//    }
//    /**
//     * 获取自动检查更新的时间间隔天数，如果为-1则表示从不自动检查更新  -- 来自SettingsPreferenceActivity
//     */
//    private static int getAutoCheckIntervalDays(Context context) {
//       // SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
//        //String maxTraceNum = preferences.getString(KEY_AUTO_CHECK_INTERVAL_DAYS, "7");
//        return Integer.parseInt("7");
//    }
}
